package org.jxf.zhaohuo.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URLEncoder;
import java.util.Enumeration;

import org.apache.http.conn.util.InetAddressUtils;
import org.jxf.zhaohuo.application.DriverApplication;
import org.jxf.zhaohuo.application.DriverBroadcastReceiver;
import org.jxf.zhaohuo.plugin.Device;
import org.jxf.zhaohuo.utils.HttpUtils;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.Process;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.util.Log;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

public class DaemonService_old extends Service {
	
	public static final String TAG = "DaemonService";

	public int count;
	public String msg;

	public String url;

	public double currLat;
	public double currLon;
	public String currLocType;
	public float currLocAccuracy;

	public double baiduLat = 0;
	public double baiduLng = 0;

	public int satelliteNum = 0;
	public int timeToFirstFix = 0;
	public long locationTime = 0;
	public String lat_lng = "";

	public String gpsStatus = "未知";

	public LocationClient mLocationClient = null;
	public MyLocationListenner myListener = new MyLocationListenner();
	
	public static String lastUrl = null;
	
	
	private WakeLock wakeLock;
	
	@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }	

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		acquireWakeLock();
		
		IntentFilter filter = new IntentFilter(Intent.ACTION_TIME_TICK); 
		DriverBroadcastReceiver receiver = new DriverBroadcastReceiver(); 
		registerReceiver(receiver, filter); 

		Log.i(TAG, "DaemonService onCreate");
		
		getPhoneDeviceInfo();
		try {
			File file = new File(DriverApplication.APP_DIR
					+ "/zhaohuo_user.txt");
			if (file.exists()) {
				BufferedReader br = new BufferedReader(new InputStreamReader(
						new FileInputStream(file), "UTF-8"));
				DriverApplication.mdn = br.readLine();// 一锟轿讹拷锟斤拷一锟斤拷

			}
		} catch (Exception e) {
			e.printStackTrace();
		}


		mLocationClient = new LocationClient(this);

		mLocationClient.setAK("F6f71c81a3fd1e0bd3bf12a3ce8eceac");
		mLocationClient.registerLocationListener(myListener);
		Log.d(TAG, "... Application onCreate... pid=" + Process.myPid());
		setLocationOption();
		mLocationClient.start();
//		mLocationClient.requestLocation();
		
	}	
	@Override
	public void onDestroy() {
		super.onDestroy();
//		releaseWakeLock();
//		Log.i(TAG, "DaemonService onDestroy");
		this.startService(new Intent(this, DaemonService_old.class));
		Log.i(TAG, "DaemonService onDestroy and restart!");
	}	
	/**
	 * 防止休眠
	 */
	private void acquireWakeLock() {
		if (wakeLock == null) {
			PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
			wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this
					.getClass().getCanonicalName());
			wakeLock.acquire();
		}
	}

	/**
	 * 强锟狡达拷锟绞憋拷锟斤拷薪锟斤拷
	 */
	private void releaseWakeLock() {
		if (wakeLock != null && wakeLock.isHeld()) {
			wakeLock.release();
			wakeLock = null;
		}
	}
	
	
	private void setLocationOption() {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setCoorType("bd09ll");
		option.setServiceName("com.baidu.location.service_v2.9");
		option.setPoiExtraInfo(true);
		if (true) {
			option.setAddrType("all");
		}

		option.setScanSpan(3000);
		option.setPriority(LocationClientOption.GpsFirst); 

		option.setPoiNumber(3);
		option.disableCache(true);
		mLocationClient.setLocOption(option);
	}


	public class MyLocationListenner implements BDLocationListener {
		int count = 0;
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;

			if (location.getLocType() != 161 && location.getLocType() != 61)
				return;
			
			if (DriverApplication.mdn == null || DriverApplication.mdn.equals("null")){
				return;
			}

			String errorCode = String.valueOf(location.getLocType());
			StringBuffer sb = new StringBuffer(256);

			sb.append("driver_mobile_trace.error_code=" + errorCode);
			sb.append("&driver_mobile_trace.loc_time=" + location.getTime());
			sb.append("&driver_mobile_trace.loc_type=" + location.getLocType());
			sb.append("&driver_mobile_trace.lat=" + location.getLatitude());
			sb.append("&driver_mobile_trace.lng=" + location.getLongitude());
			sb.append("&driver_mobile_trace.radius=" + location.getRadius());
			if (location.getLocType() == BDLocation.TypeGpsLocation) {
				sb.append("&driver_mobile_trace.speed=" + location.getSpeed());
				sb.append("&driver_mobile_trace.satellite_num"
						+ location.getSatelliteNumber());
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
				String loc_desc = location.getAddrStr();
//				Log.i(TAG, loc_desc);
				try {
					
					loc_desc = URLEncoder.encode(loc_desc, "utf-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				sb.append("&driver_mobile_trace.loc_desc="
						+ loc_desc);
			}

			sb.append("&driver_mobile_trace.sid=" + Device.sid);
			sb.append("&driver_mobile_trace.nid=" + Device.nid);
			sb.append("&driver_mobile_trace.bid=" + Device.bid);

			sb.append("&driver_mobile_trace.imsi=" + Device.imsi);
			sb.append("&driver_mobile_trace.imei=" + Device.imei);
			sb.append("&driver_mobile_trace.uuid=" + Device.uuid);
			sb.append("&driver_mobile_trace.mdn=" + DriverApplication.mdn);
			sb.append("&driver_mobile_trace.os_version=" + android.os.Build.VERSION.RELEASE);
			
			url = "http://" + DriverApplication.IP+ "/updateLocation.action?" + sb.toString();
			
			if (url.equals(lastUrl)){
				return;
			}
			lastUrl = url;
			Log.i(TAG, url);
			
			new Thread() {
				@Override
				public void run() {
					try {
						String result = HttpUtils.getHtml4Url(url);
//						sendXML();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					handler.sendEmptyMessage(0);
				}
			}.start();

		}

		

		
		@Override
		public void onReceivePoi(BDLocation arg0) {
			// TODO Auto-generated method stub

		}

	}

	
	
	// 锟斤拷锟斤拷Handler锟斤拷锟斤拷
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
		}
	};

	public String getUuid() {
		String uuid = Settings.Secure.getString(this.getContentResolver(),
				android.provider.Settings.Secure.ANDROID_ID);
		return uuid;
	}

	public void getPhoneDeviceInfo() {
		TelephonyManager tm = (TelephonyManager) this
				.getSystemService(Context.TELEPHONY_SERVICE);
		Device.imei = tm.getDeviceId();
		if (Device.imei == null) {
			Device.imei = "";
		}

		Device.imsi = tm.getSubscriberId();
		if (Device.imsi == null) {
			Device.imsi = "";
		}

		int type = tm.getNetworkType();
		//涓浗鐢典俊涓篊TC
		//NETWORK_TYPE_EVDO_A鏄腑鍥界數淇�G鐨刧etNetworkType
		//NETWORK_TYPE_CDMA鐢典俊2G鏄疌DMA
		if (type == TelephonyManager.NETWORK_TYPE_EVDO_A
				|| type == TelephonyManager.NETWORK_TYPE_CDMA
				|| type == TelephonyManager.NETWORK_TYPE_1xRTT) {
			Device.op = "鐢典俊";

		}
		//绉诲姩2G鍗�+ CMCC + 2
		//type = NETWORK_TYPE_EDGE
		else if (type == TelephonyManager.NETWORK_TYPE_EDGE) {
			Device.op = "绉诲姩";

		}
		//鑱旈�鐨�G缁忚繃娴嬭瘯 China Unicom 1 NETWORK_TYPE_GPRS
		else if (type == TelephonyManager.NETWORK_TYPE_GPRS) {
			Device.op = "鑱旈�";

		} else {
			Device.op = "鏈煡";
		}

		try {
			// CellLocation cellLocation = tm.getCellLocation();
			Log.i("hello", "NetworkCountryIso = " + tm.getNetworkCountryIso());// cn
			String networkOp = tm.getNetworkOperator();
			Log.i("hello", "networkOp = " + tm.getNetworkCountryIso());
			int mcc = Integer.valueOf(networkOp.substring(0, 3));
			int mnc = Integer.valueOf(networkOp.substring(3, 5));
			Log.i("hello", "mobile_country_code mcc = " + mcc);// mobile_country_code
			Log.i("hello", "mobile_network_code mnc = " + mnc);// mobile_network_code

			// CellLocation cellLocation = tm.getCellLocation();
			CdmaCellLocation cellLocation = ((CdmaCellLocation) tm
					.getCellLocation());
			int cellId = cellLocation.getBaseStationId();
			int cellLat = cellLocation.getBaseStationLatitude() / 14400;
			int cellLng = cellLocation.getBaseStationLongitude() / 14400;
			int networkId = cellLocation.getNetworkId();
			int systemId = cellLocation.getSystemId();
			Log.i("hello", "cellId = " + cellId);
			Log.i("hello", "cellLat = " + cellLat);
			Log.i("hello", "cellLng = " + cellLng);
			Log.i("hello", "locationAreaCode networkId = " + networkId);
			Log.i("hello", "mobileNetworkCode systemId = " + systemId);

			Device.cellInfo = "sid = " + systemId + ",nid = " + networkId
					+ ",bid = " + cellId;
			Device.sid = String.valueOf(systemId);
			Device.nid = String.valueOf(networkId);
			Device.bid = String.valueOf(cellId);

			Device.ip = getLocalIpAddress();

			Device.uuid = this.getUuid();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()
							&& InetAddressUtils.isIPv4Address(inetAddress
									.getHostAddress())) {
						String ip = inetAddress.getHostAddress().toString();
						return ip;
					}
				}
			}
		} catch (SocketException ex) {

		}
		return null;
	}
	

}
